using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using AutoMapper;
using FytSoa.Application.Sys.Dto;
using FytSoa.Common;
using FytSoa.Model.Sys;
using FytSoa.Repository.Interfaces;
using FytSoa.SugarCore;
using SqlSugar;

namespace FytSoa.Application.Sys
{
    public class SysAdminService : MyContext, ISysAdminService
    {
        private readonly IBaseRepository<SysAdmin> _thisRepository;
        private readonly ISysPostService _postService;
        private readonly ISysRoleService _roleService;
        private readonly ISysOrganizeService _organizeService;
        public SysAdminService(IBaseRepository<SysAdmin> thisRepository, ISysPostService postService
            , ISysRoleService roleService, ISysOrganizeService organizeService)
        {
            _thisRepository = thisRepository;
            _postService = postService;
            _roleService = roleService;
            _organizeService = organizeService;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ApiResult<Page<SysAdminDto>>> PageList(SysAdminWhereParam param)
        {
            var result = new ApiResult<Page<SysAdminDto>>();
            try
            {
                var list =await Db.Queryable<SysAdmin>()
                    .Where(m=>!m.IsDel)
                    .WhereIF(!string.IsNullOrEmpty(param.key),m=>m.LoginAccount.Contains(param.key) || m.Mobile==param.key || m.Email.Contains(param.key) || m.FullName.Contains(param.key))
                    .WhereIF(param.status!=0,m=>m.Status== (param.status == 1))
                    .Mapper(m=>m.organize,m=>m.OrganizeId)
                    .ToPageAsync(param.page, param.limit);
                //MapperConfiguration config = new MapperConfiguration(cfg => cfg.CreateMap<SysAdmin,SysAdminDto>().ForMember(d=>d.OrganizeName,opt=>opt.MapFrom(s=>s.organize.Name)));
                //result.Data.Items = config.CreateMapper().Map<List<SysAdminDto>>(list);
                result.Data = new Page<SysAdminDto>()
                {
                    ItemsPerPage = list.ItemsPerPage,
                    TotalItems = list.TotalItems,
                    TotalPages = list.TotalPages,
                    CurrentPage = list.CurrentPage,
                    Items = list.Items.MapToList<SysAdmin, SysAdminDto>()
                };
            }
            catch (Exception ex)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> Add(SysAdminParam model)
        {
            var result = new ApiResult<string>();
            try
            {
                //判断用户是否存在
                var isExist = await _thisRepository.IsExistAsync(m=>m.LoginAccount==model.LoginAccount);
                if (isExist)
                {
                    result.StatusCode = (int)HttpStatusCode.PaymentRequired;
                    result.Message = "登录账号已存在，请更换~~";
                    return result;
                }
                model.Id = Unique.Id();
                var adminModel = model.MapTo<SysAdminParam, SysAdmin>(m=>m.organize);
                adminModel.RoleId = model.Role;
                adminModel.PostId = model.Post;
                adminModel.LoginPassWord = DES3Encrypt.EncryptString(adminModel.LoginPassWord);
                adminModel.OrganizeId = model.Organize;
                adminModel.CreateUser = "admin";
                await _thisRepository.AddAsync(adminModel);
            }
            catch (Exception ex)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> Modify(SysAdminParam model)
        {
            var result = new ApiResult<string>();
            try
            {
                //判断用户是否存在
                var isExist = await _thisRepository.IsExistAsync(m => m.LoginAccount == model.LoginAccount && m.Id!=model.Id);
                if (isExist)
                {
                    result.StatusCode = (int)HttpStatusCode.PaymentRequired;
                    result.Message = "登录账号已存在，请更换~~";
                    return result;
                }
                var adminModel = model.MapTo<SysAdminParam, SysAdmin>(m=>m.organize);
                adminModel.RoleId = model.Role;
                adminModel.PostId = model.Post;
                adminModel.LoginPassWord = DES3Encrypt.EncryptString(adminModel.LoginPassWord);
                adminModel.OrganizeId = model.Organize;
                await _thisRepository.UpdateAsync(adminModel, m => new { m.CreateUser, m.CreateTime, m.IsDel,m.LoginCount,m.UpLoginTime,m.LoginTime });
            }
            catch (Exception ex)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 查询实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<SysAdminSelect>> GetModel(string id)
        {
            var result = new ApiResult<SysAdminSelect>();
            try
            {
                var adminModel = await _thisRepository.GetModelAsync(m=>m.Id==id);
                var postList = await _postService.Select();
                var roleList = await _roleService.GroupSelectAll();
                var organize = await _organizeService.GetSelect();
                result.Data = new SysAdminSelect()
                {
                    admin=adminModel,
                    post= postList.Data,
                    role=roleList.Data,
                    organize=organize.Data
                };
            }
            catch (Exception ex)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> Delete(List<string> ids)
        {
            var result = new ApiResult<string>();
            try
            {
                //假删除
                await _thisRepository.UpdateAsync(m => new SysAdmin() { IsDel = true }, m => ids.Contains(m.Id));
            }
            catch (Exception ex)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                result.Message = ex.Message;
            }
            return result;
        }

    }
}
